package com.example.androidtvdemo.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.View;

import androidx.leanback.widget.VerticalGridView;


/**
 * Create by dr on 2021/12/24
 * Desc : 博客网格列表
 */
public class BlogGridView extends VerticalGridView {
    private static final String TAG = "BlogGridView";
    private int numColumns;

    public BlogGridView(Context context) {
        super(context);
    }

    public BlogGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BlogGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setNumColumns(int numColumns) {
        super.setNumColumns(numColumns);
        this.numColumns = numColumns;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        try {
            // 按键按下，切向右
            if (KeyEvent.ACTION_DOWN == event.getAction() && KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()) {
                // 获取当前vg的聚焦的view
                View focusedChild = getFocusedChild();
                // 搜索向右方向的下个焦点
                View nextFocus = FocusFinder.getInstance().findNextFocus(this, focusedChild, FOCUS_RIGHT);
                if (nextFocus == null) {
                    //当前聚焦的view,是不是列的倍数
                    LayoutManager layoutManager = getLayoutManager();
                    if (layoutManager == null) {
                        return false;
                    }
                    // 获得当前聚焦的item在整个rv中的位置
                    int position = layoutManager.getPosition(focusedChild);
                    // 如果位置刚好是边界，比如设置column 4 那就是position + 1 然后% == 0 证明到了右边
                    if ((position + 1) % numColumns == 0) {
                        Log.d(TAG, "->> 右边尽头了 edge " + position);
                        if (mOnEdgeInterceptListener != null) {
                            mOnEdgeInterceptListener.onEdgeRight();
                        }
                    } else {
                        //右边聚焦切换上一行情况,如果不足一排4个,要特殊处理
                        if (getAdapter().getItemCount() <= numColumns) {
                            if (mOnEdgeInterceptListener != null) {
                                mOnEdgeInterceptListener.onEdgeRight();
                            }
                        } else {
                            int targetIndex = position - numColumns + 1;
                            View edgeRightView = layoutManager.findViewByPosition(targetIndex);
                            if (edgeRightView != null) {
                                boolean requestFocus = edgeRightView.requestFocus();
                                Log.i(TAG, "->>>>> 右边尽头了,修复聚焦" + position + "," + targetIndex + "," + requestFocus);
                            }
                        }
                        Log.i(TAG, "->>>>> 右边尽头了 " + position);
                    }
                    return true;
                }
            } else if (KeyEvent.ACTION_DOWN == event.getAction() && KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()) {
                //按下
                View focusedChild = getFocusedChild();
                View nextFocus = FocusFinder.getInstance().findNextFocus(this, focusedChild, FOCUS_DOWN);
                if (nextFocus == null) {
                    LayoutManager layoutManager = getLayoutManager();
                    if (layoutManager == null || focusedChild == null || focusedChild.getLayoutParams() == null) {
                        return false;
                    }
                    int itemCount = getAdapter().getItemCount();
                    int position = layoutManager.getPosition(focusedChild);
                    int lastRowCount = itemCount % numColumns;
                    //如果等于0,就是刚好填满
                    if (lastRowCount != 0 && position < (itemCount - lastRowCount)) {
                        //那就是已经最后排了,给系统处理,否则
                        int dx = itemCount - 1 - position;
                        //dx就是剩下的item数目,这个数目必须小于span count 4
                        Log.i(TAG, "->>>>> 尽头了,剩下" + dx + "," + position + "," + itemCount);
                        if (dx > 0 && dx < numColumns) {
                            //直接聚焦最后一个就行了
                            View edgeBottomView = layoutManager.findViewByPosition(itemCount - 1);
                            if (edgeBottomView != null) {
                                boolean focus = edgeBottomView.requestFocus();
                                Log.i(TAG, "->>>>> 尽头了, " + focus);
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchKeyEvent(event);
    }

    private OnEdgeInterceptListener mOnEdgeInterceptListener;

    public void setOnEdgeInterceptListener(OnEdgeInterceptListener onEdgeInterceptListener) {
        mOnEdgeInterceptListener = onEdgeInterceptListener;
    }

    public interface OnEdgeInterceptListener {
        void onEdgeRight();
    }
}
